package com.ruoyi.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.BasicFamily;
import com.ruoyi.basic.domain.BasicSalary;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basic.mapper.BasicInsuranceMapper;
import com.ruoyi.basic.domain.BasicInsurance;
import com.ruoyi.basic.service.IBasicInsuranceService;
import com.ruoyi.common.core.text.Convert;

/**
 * 保险基数Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-01-17
 */
@Service
public class BasicInsuranceServiceImpl extends ServiceImpl<BasicInsuranceMapper, BasicInsurance> implements IBasicInsuranceService
{

    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询保险基数
     * 
     * @param insuranceId 保险基数主键
     * @return 保险基数
     */
    @Override
    public BasicInsurance selectBasicInsuranceByInsuranceId(Long insuranceId)
    {
        return baseMapper.selectBasicInsuranceByInsuranceId(insuranceId);
    }

    /**
     * 查询保险基数列表
     * 
     * @param basicInsurance 保险基数
     * @return 保险基数
     */
    @Override
    public List<BasicInsurance> selectBasicInsuranceList(BasicInsurance basicInsurance)
    {
        return baseMapper.selectBasicInsuranceList(basicInsurance);
    }

    /**
     * 新增保险基数
     * 
     * @param basicInsurance 保险基数
     * @return 结果
     */
    @Override
    public int insertBasicInsurance(BasicInsurance basicInsurance)
    {
        if (basicInsurance.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<BasicInsurance>().set(BasicInsurance::getIsDefault, "N")
                    .eq(BasicInsurance::getUserId, basicInsurance.getUserId()).eq(BasicInsurance::getIsDefault, "Y"));
        }
        basicInsurance.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicInsurance);
    }

    /**
     * 修改保险基数
     * 
     * @param basicInsurance 保险基数
     * @return 结果
     */
    @Override
    public int updateBasicInsurance(BasicInsurance basicInsurance)
    {
        if (basicInsurance.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<BasicInsurance>().set(BasicInsurance::getIsDefault, "N")
                    .eq(BasicInsurance::getUserId, basicInsurance.getUserId()).eq(BasicInsurance::getIsDefault, "Y")
                    .ne(BasicInsurance::getInsuranceId, basicInsurance.getInsuranceId()));
        }
        basicInsurance.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicInsurance);
    }

    /**
     * 批量删除保险基数
     * 
     * @param insuranceIds 需要删除的保险基数主键
     * @return 结果
     */
    @Override
    public int deleteBasicInsuranceByInsuranceIds(String insuranceIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(insuranceIds)));
    }

    /**
     * 删除保险基数信息
     * 
     * @param insuranceId 保险基数主键
     * @return 结果
     */
    @Override
    public int deleteBasicInsuranceByInsuranceId(Long insuranceId)
    {
        return baseMapper.deleteById(insuranceId);
    }

    /**
     * 导入用户保险基数
     *
     * @param insuranceList 用户保险基数数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importInsurance(List<BasicInsurance> insuranceList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(insuranceList) || insuranceList.size() == 0)
        {
            throw new ServiceException("导入用户保险基数数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicInsurance insurance : insuranceList)
        {
            try
            {
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, insurance.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    insurance.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + insurance.getUserName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(insurance.getInsuranceTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date insuranceTime = dateFormat.parse(insurance.getInsuranceTime());
                    insurance.setInsuranceTime(DateUtils.parseDateToStr("yyyy-MM-dd", insuranceTime));
                }

                // 验证是否存在保险基数
                BasicInsurance info = baseMapper.selectOne(new LambdaQueryWrapper<BasicInsurance>()
                        .eq(BasicInsurance::getInsuranceTime, insurance.getInsuranceTime())
                        .eq(BasicInsurance::getUserId, insurance.getUserId()));
                if (StringUtils.isNull(info))
                {
                    insurance.setCreateBy(operName);
                    this.insertBasicInsurance(insurance);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + insurance.getUserName() + "保险基数 " + insurance.getInsurance() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    insurance.setInsuranceId(info.getInsuranceId());
                    insurance.setUpdateBy(operName);
                    this.updateBasicInsurance(insurance);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + insurance.getUserName() + "保险基数 " + insurance.getInsurance() + " 修改成功");
                }
                else
                {
                    failureNum++;
                    successMsg.append("<br/>" + successNum + "、" + insurance.getUserName() + "保险基数 " + insurance.getInsurance() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + insurance.getUserName() + " 岗位工资导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
